#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
//单个节点的结构体的定义
typedef struct BinaryTreeNode
{
	int val;
	struct BinaryTreeNode* left;
	struct BinaryTreeNode* right;

}BTNode;
//创建二叉树节点函数
BTNode* BuyNode(int x)
{
	//为节点开辟空间
	BTNode* NewNode = (BTNode*)malloc(sizeof(BTNode));
	//开辟成败的检测
	if (NewNode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	//对节点的初始化
	NewNode->left = NULL;
	NewNode->right = NULL;
	NewNode->val = x;
	//返回节点
	return NewNode;
}
//先序遍历
void PrevOrder(BTNode* root)
{
	if (root == NULL)
	{
		return;
	}

	printf("%d ", root->val);
	PrevOrder(root->left);
	PrevOrder(root->right);
}

//中序遍历（左子树，根，右子树）
//void InOrder(BTNode* root)
//{
//	if (root == NULL)
//	{
//		return;
//	}
//
//	PrevOrder(root->left);
//	printf("%d ", root->val);
//	PrevOrder(root->right);
//}

void InOrder(BTNode* root)
{
	if (root == NULL)
	{
		return;
	}

	InOrder(root->left);
	printf("%d ", root->val);
	InOrder(root->right);
}
//后序遍历（左子树，右子树，根）
void PostOrder(BTNode* root)
{
	if (root == NULL)
	{
		return;
	}

	PostOrder(root->left);
	PostOrder(root->right);
	printf("%d ", root->val);
}
//求节点个数
int TreeSize(BTNode* root)
{
	return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}
// 叶子节点个数
int TreeLeafSize(BTNode* root)
{
	if (root == NULL)
		return 0;

	if (root->left == NULL && root->right == NULL)
	{
		return 1;
	}

	return TreeLeafSize(root->left) + TreeLeafSize(root->right);
}
// 第k层的节点个数
int TreeKLevel(BTNode* root, int k)
{
	assert(k > 0);

	if (root == NULL)
		return 0;

	if (k == 1)
	{
		return 1;
	}

	return TreeKLevel(root->left, k - 1)
		+ TreeKLevel(root->right, k - 1);
}
// 二叉树销毁
void TreeDestroy(BTNode* root)
{
	if (root == NULL)
	{
		return;
	}

	TreeDestroy(root->left);
	TreeDestroy(root->right);
	free(root);
	//root = NULL;
}
// 二叉树查找值为x的结点
BTNode* TreeFind(BTNode* root, int x)
{
	//节点为空，返回NULL
	if (root == NULL)
		return NULL;
	//再判断值是否为x
	if (root->val == x)
		return root;
	//向下递进继续查找
	//创建一个ret来接收左右子树查找的返回值
	BTNode* ret = NULL;
	//左子树的查找
	ret = TreeFind(root->left, x);
	if (ret)
		return ret;
	//右子树的查找
	ret = TreeFind(root->right, x);
	if (ret)
		return ret;
	//所有节点都没找到，返回NULL
	return NULL;
}
int main()
{
	BTNode* n1 = BuyNode(1);
	BTNode* n2 = BuyNode(2);
	BTNode* n3 = BuyNode(3);
	BTNode* n4 = BuyNode(4);
	BTNode* n5 = BuyNode(5);
	BTNode* n6 = BuyNode(6);

	n1->left = n2;
	n1->right = n4;
	n2->left = n3;
	n4->left = n5;
	n4->right = n6;


	TreeDestroy(n1);
	n1 = NULL;

	return 0;
}